import CodoBase from "../../../lib/CodoBase";
import CodoError from "../../../lib/CodoError";
import { Wechat } from "../wechat";

export default class CodoWechatGzhWebPage extends CodoBase {
	/** 公众号根据code获取openId
	 * - 适用于h5网页登录公众号时授权
	 * - https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
	 */
	async getOpenIdByCode(appId: string, secret: string, code: string) {
		const wechatGetOpenIdUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${secret}&code=${code}&grant_type=authorization_code`;
		const res = await this.app.curl<Wechat.gzh.response.IGetOpenIdByCodeSucess | Wechat.ICommonRespnose>(wechatGetOpenIdUrl, {
			method: "GET",
			dataType: "json",
		});
		if ("errcode" in res.data && res.data.errcode) {
			throw new CodoError(`wechat gzh getOpenIdByCode  error %s %s`, res.data.errcode, res.data.errmsg);
		}
		const data = res.data;
		return data as Wechat.gzh.response.IGetOpenIdByCodeSucess;
	}
}
